﻿using ModelLayer;
using System;
using System.Data;
using System.Data.SqlClient;

namespace DataAccessObjectLayer
{
    public class DBCity : DBClass
    {
        /// <summary>
        /// Gets a city from the database with a given postalcode.
        /// </summary>
        /// <param name="postalcode">The postalcode of the city.</param>
        public City GetCityFromPostalCode(int postalcode)
        {
            SqlParameter paramPostalCode = new SqlParameter("@PostalCode", SqlDbType.Int) { Value = postalcode };
            string wClause = "PostalCode = " + paramPostalCode.Value;
            return (City)SingleWhere(wClause);
        }

        /// <summary>
        /// Gets a city from the database with a given name.
        /// </summary>
        /// <param name="cityName">Name of the city.</param>
        public City GetCityFromName(string cityName)
        {
            SqlParameter paramCityName = new SqlParameter("@CityName", SqlDbType.Int) { Value = cityName };
            string wClause = "City = " + paramCityName;
            return (City)SingleWhere(wClause);
        }

        /// <summary>
        /// Builds a query with a 'where'-clause.
        /// </summary>
        /// <param name="wClause">The where clause.</param>
        protected override string BuildQuery(string wClause)
        {
            String query = "SELECT city, postalcode FROM city ";
            if (wClause.Length > 0)
            {
                query += "WHERE " + wClause;
            }
            return query;
        }

        /// <summary>
        /// Builds an object from either a dataset or a datareader The bool 'connected' defines if
        /// it is one or the other
        /// </summary>
        /// <param name="dataSetOrDataReader"></param>
        /// <param name="connected"></param>
        protected override object BuildObject(object dataSetOrDataReader, bool connected)
        {
            City city = null;

            if (connected)
            {
                SqlDataReader dataReader = dataSetOrDataReader as SqlDataReader;
                if (dataReader != null)
                    city = new City
                    {
                        CityName = (string)dataReader["City"],
                        PostalCode = (int)dataReader["PostalCode"],
                    };
            }
            else
            {
                DataRow dataRow = dataSetOrDataReader as DataRow;
                if (dataRow != null)
                    city = new City
                    {
                        CityName = (string)dataRow["City"],
                        PostalCode = (int)dataRow["PostalCode"],
                    };
            }

            object o = city;
            return o;
        }
    }
}